package com.fingard.dsp.bank.directbank.klb01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.reqrespobj.single.*;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.net.ConnState;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.math.BigDecimal;

public class KLB01SinglePay extends KLB01Base implements ISinglePay {
    @Override
    public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);
        RetAtsSglDetail tmpRetDetail;
        tmpRetDetail = externalPayments(p_req1908);
        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    //190802对外支付
    private RetAtsSglDetail externalPayments(ReqSingle p_req1908) throws Exception {
        RetAtsSglDetail retDetail = new RetAtsSglDetail();
        if (p_req1908.singleDetail.sameBnk.equals("1")) {
            bankInnerTransfer(p_req1908, retDetail);   //行内转账
        } else {//跨行
            crossBankTransfer(p_req1908, retDetail);   //跨行转账
        }
        return retDetail;
    }

    //同行转账
    private RetAtsSglDetail bankInnerTransfer(ReqSingle p_req1908, RetAtsSglDetail retDetail) throws Exception {
        bnkVersion = "0.0.0.1";
        bank = "KLB";
        bnkOrgId = bankFront.corpNo;
        bnkoOrgName = bankFront.org;
        bnkTxCode = "1030";
        bnkTxPackNo = p_req1908.singleDetail.askNumber;

        try {
            XmlTextWriter xmlWriter = new XmlTextWriter();
            writeCommonHeader(xmlWriter);

            XElement tmpXElement = new XElement("body", "");
            tmpXElement.addChild(new XElement("Flag1", "6"));//Flag1  借方帐户来源 3：存款帐户 ；4：卡 ；6：未知（上送的帐号在无法确定子系统的情况下，由主机判断）
            tmpXElement.addChild(new XElement("AcctNo1", p_req1908.singleDetail.payAct)); //AcctNo1	借方帐号/卡号
            tmpXElement.addChild(new XElement("SubAcct1", ""));//SubAcct1 	借方款项代码   没有就不赋值
            tmpXElement.addChild(new XElement("AcctSeqNo1", "")); //AcctSeqNo1	借方卡内帐户序号  没有就不赋值
            tmpXElement.addChild(new XElement("Passwd1", ""));//Passwd1	借方帐号/卡号密码   没有就不赋值
            tmpXElement.addChild(new XElement("Ccy1", convertCurToBank(p_req1908.singleDetail.payCur))); //Ccy1  	借方币种
            tmpXElement.addChild(new XElement("Amt1", p_req1908.singleDetail.payAmount));//Amt1 	借方交易金额 17,2
            tmpXElement.addChild(new XElement("CheckFlag", "0")); //CheckFlag	是否检查密码  ‘0’ �C 不检查 ；‘1’ �C 检查借方密码 ；‘2’ �C 检查贷方密码
            tmpXElement.addChild(new XElement("Flag2", "6")); //Flag2 	贷方帐户来源   3：存款帐户 ；4：卡 ；6：未知（上送的帐号在无法确定子系统的情况下，由主机判断）
            tmpXElement.addChild(new XElement("AcctNo2", p_req1908.singleDetail.recAct)); //AcctNo2	贷方帐号/卡号
            tmpXElement.addChild(new XElement("SubAcct2", "")); //SubAcct2 	贷方款项代码  没有就不赋值
            tmpXElement.addChild(new XElement("AcctSeqNo2", "")); //AcctSeqNo2	贷方卡内帐户序号  没有就不赋值
            tmpXElement.addChild(new XElement("Passwd2", "")); //Passwd2 	贷方帐号/卡号密码  没有就不赋值
            tmpXElement.addChild(new XElement("Ccy2", convertCurToBank(p_req1908.singleDetail.recCur))); //Ccy2	贷方币种
            tmpXElement.addChild(new XElement("Amt2", p_req1908.singleDetail.payAmount)); //Amt2 	贷方交易金额   17,2
            tmpXElement.addChild(new XElement("MemoCode", "1008")); //MemoCode 	摘要码  1008-转帐
            tmpXElement.addChild(new XElement("MsgCont", p_req1908.singleDetail.memo)); //MsgCont	备注信息
            tmpXElement.addChild(new XElement("Flag3", "0")); //Flag3  	交易类型   0-正常；1-联动

            nodeAnalysis(p_req1908.singleDetail.srcXElement, tmpXElement, getCharset());
            xmlWriter.writeXElement(tmpXElement);


            xmlWriter.writeEndElement();
            xmlWriter.writeEndDocument();
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());//发送给银行
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    retDetail.respCode = "0";
                    retDetail.respInfo = tmpBkReader.getFirstText("/root/head/RetMsg").trim();
                    retDetail.reqSeqID = tmpBkReader.getFirstText("/root/head/TxPackNo");

                    retDetail.transState = tmpBkReader.getFirstText("/root/head/RetCode");
                    retDetail.payInfoCode = tmpBkReader.getFirstText("/root/head/RetCode");
                } else {
                    retDetail.respCode = "-1";
                    retDetail.respInfo = tmpSbMsg.toString();
                }
            } else if (tmpStrRet[0].equals(ConnState.FAIL)) {
                retDetail.respCode = "0";
                retDetail.respInfo = tmpStrRet[1];
                retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                retDetail.transState = PaymentState.FAIL_Payment;
                retDetail.payInfoCode = tmpStrRet[0];
            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            retDetail.respCode = "-1";
            retDetail.respInfo = e.getMessage();
            e.printStackTrace();
            WriteBankLogLn(e);
        }
        return retDetail;
    }

    // 跨行转账
    private RetAtsSglDetail crossBankTransfer(ReqSingle p_req1908, RetAtsSglDetail retDetail) throws Exception {
        bnkVersion = "0.0.0.1";
        bank = "KLB";
        bnkOrgId = bankFront.corpNo;
        bnkoOrgName = bankFront.org;
        bnkTxCode = "8605";
        bnkTxPackNo = p_req1908.singleDetail.askNumber;
        try {
            XmlTextWriter xmlWriter = new XmlTextWriter();// 发银行报文的XML对象
            writeCommonHeader(xmlWriter);
            XElement tmpXElement = new XElement("body", "");
            String flag = "1";
            if (new BigDecimal(p_req1908.singleDetail.payAmount).compareTo(new BigDecimal(50000)) <= 0) {
                flag = "0";
            }
            tmpXElement.addChild(new XElement("Flag", flag));// Flag 大小额标志

            tmpXElement.addChild(new XElement("Amount", p_req1908.singleDetail.payAmount));// Amount
            // 交易金额
            tmpXElement.addChild(new XElement("BusiList", "11"));// BusiList 业务种类

            tmpXElement.addChild(new XElement("Ccy", convertCurToBank(p_req1908.singleDetail.recCur)));// Ccy
            // 币种
            tmpXElement.addChild(new XElement("CustomId", bankFront.corporation));// CustomId
            // 客户号
            tmpXElement.addChild(new XElement("CustomType", p_req1908.singleDetail.isPrivate));// CustomType
            // 客户类别
            // 1-个人；2-对公；3-同业
            tmpXElement.addChild(new XElement("DrwType", " "));// DrwType 支取方式 1 凭密
            // ********
            tmpXElement.addChild(new XElement("MbfeMemo", ""));// MbfeMemo 附言
            // 客户填写的附言 ********
            tmpXElement.addChild(new XElement("MsgAttr", p_req1908.singleDetail.paySpd));// MsgAttr
            // 优先级别
            tmpXElement.addChild(new XElement("OpenBrc", p_req1908.singleDetail.cnapsName));// OpenBrc
            // 账户开户行
            tmpXElement.addChild(new XElement("PayAccName", p_req1908.singleDetail.payName));// PayAccName
            // 付款人户名
            tmpXElement.addChild(new XElement("AcctNo", p_req1908.singleDetail.payAct));// AcctNo
            // 付款人账户
            tmpXElement.addChild(new XElement("PayAddress", " "));// PayAddress
            // 付款人地址 可不填
            tmpXElement.addChild(new XElement("PayPasswd", ""));// PayPasswd 密码
            // 支取方式为密码时必输
            tmpXElement.addChild(new XElement("RecvAccName", p_req1908.singleDetail.recName));// RecvAccName
            // 收款人户名
            tmpXElement.addChild(new XElement("RecvAccNo", p_req1908.singleDetail.recAct));// RecvAccNo
            // 收款人账户
            tmpXElement.addChild(new XElement("RecvAddress", ""));// RecvAddress
            // 收款人地址 没有可不填
            tmpXElement.addChild(new XElement("RecvBankNo", p_req1908.singleDetail.cnapsCode));// RecvBankNo
            // 收款行行号
            tmpXElement.addChild(new XElement("SubAcct", ""));// SubAcct 款项帐号 没有可不填
            // ********
            tmpXElement.addChild(new XElement("Amt1", "5.00"));// Amt1 手续费 17,2 ********
            String isPrivate = p_req1908.singleDetail.isPrivate;
            if (!("1").equals(isPrivate) && !("2").equals(isPrivate)) {
                isPrivate = "0";
            }
            tmpXElement.addChild(new XElement("Flag1", isPrivate));// Flag1 收费类别
            // 1-个人收费；2-对公；若不区分填0
            // ********

            nodeAnalysis(p_req1908.singleDetail.srcXElement, tmpXElement, getCharset());
            xmlWriter.writeXElement(tmpXElement);


            xmlWriter.writeEndElement();
            xmlWriter.writeEndDocument();
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());// 发送银行
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    retDetail.respCode = "0";
                    retDetail.respInfo = tmpBkReader.getFirstText("/root/head/RetMsg").trim();
                    /*retDetail.reqSeqID = p_req1908.singleDetail.askNumber;*/
                    retDetail.reqSeqID = tmpBkReader.getFirstText("/root/head/TxPackNo");
                    ;

                    retDetail.transState = tmpBkReader.getFirstText("/root/head/RetCode");// 支付状态码
                    retDetail.payInfoCode = retDetail.transState; // 支付信息码
                    /*retDetail.transAmt=tmpBkReader.getFirstText("/root/body/TrsAmt");//发生额*/
                } else {
                    retDetail.respCode = "-1";
                    retDetail.respInfo = tmpSbMsg.toString();
                }
            } else if (tmpStrRet[0].equals(ConnState.FAIL)) {
                retDetail.respCode = "0";
                retDetail.respInfo = tmpStrRet[1];
                retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
                retDetail.transState = PaymentState.FAIL_Payment;
                retDetail.payInfoCode = tmpStrRet[0];
            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            retDetail.respCode = "-1";
            retDetail.respInfo = e.getMessage();
            e.printStackTrace();
            WriteBankLogLn(e);
        }

        return retDetail;
    }

    //单笔支付状态查询 1944
    @Override
    public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception {
        RetAtsSingle retAts = new RetAtsSingle(p_req1944.reqHeader);
        RetAtsSglDetail retDetail = new RetAtsSglDetail();
        try {
            bnkVersion = "0.0.0.1";
            bank = "KLB";
            bnkOrgId=bankFront.corpNo;
            bnkoOrgName=bankFront.org;
            bnkTxCode = "1256";
            bnkTxPackNo = getQryTransID();//指令序列号

            XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
            writeCommonHeader(xmlWriter);
            xmlWriter.writeStartElement("body");
            xmlWriter.writeElementString("TranDate", Format.Date10Format.format(p_req1944.getBgnDateTime()));//交易日期
            xmlWriter.writeElementString("TxPackNoQuery", p_req1944.askNumber);//所要查询的指令包序列号
            String isameBank = p_req1944.sameBnk;

            if ("0".equals(isameBank)) {
                isameBank = "2";
            } else {
                isameBank = "1";
            }
            xmlWriter.writeElementString("Flag", isameBank);//1-同行转账 ；2-跨行转账


            xmlWriter.writeEndElement();
            xmlWriter.writeEndDocument();

            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String returnCode = tmpBkReader.getFirstText("/root/head/RetCode");
                    String returnMsg = tmpBkReader.getFirstText("/root/head/RetMsg").trim();
                    //结果状态 N-记录不存在 行内 0-成功1-失败
                    // 大额
                    //1_已登记
                    //2_已复核
                    //3_已发送
                    //4_发送失败
                    //5_滞留
                    //6_已清算
                    //7-排队
                    //8_排队取消
                    //r_人行拒绝
                    //k_密押错
                    //m_抹帐
                    String status = tmpBkReader.getFirstText("/root/body/Status");
                    retDetail.respCode = "0";
                    retDetail.respInfo = returnMsg;
                    retDetail.payInfoCode = returnCode;
                    retDetail.transState = isameBank + "+" + returnCode + "+" + status;
                    retDetail.reqSeqID = p_req1944.askNumber;
                } else {
                    retDetail.respCode = "-1";
                    retDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = tmpStrRet[1];
            }

        } catch (Exception e) {
            retDetail.respCode = "-1";
            retDetail.respInfo = e.getMessage();
            e.printStackTrace();
            WriteBankLogLn(e);
        }

        retAts.writeRetDetail(retDetail);
        return retAts;
    }


    @Override
    public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
        return null;
    }

    @Override
    public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
        return null;
    }
}